package cn.edu.gues.infosystam.controller;

import cn.edu.gues.infosystam.entity.Report;
import cn.edu.gues.infosystam.entity.Task;
import cn.edu.gues.infosystam.entity.Template;
import cn.edu.gues.infosystam.entity.User;
import cn.edu.gues.infosystam.service.ReportService;
import cn.edu.gues.infosystam.service.TaskService;
import cn.edu.gues.infosystam.service.TemplateService;
import cn.edu.gues.infosystam.utils.PinYin;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("Download")
public class ExcelController {

    @Autowired
    private TaskService taskService;

    @Autowired
    private ReportService reportService;

    @Autowired
    private TemplateService templateService;

    /**
     * Excel表格导出接口
     * http://localhost:8080/ExcelDownload
     * @param response response对象
     * @throws IOException 抛IO异常
     */
    @RequestMapping("/Excel/{taskId}")
    public void excelDownload(@PathVariable Integer taskId, HttpSession httpSession, HttpServletResponse response) throws IOException {
        User userInfo = (User)httpSession.getAttribute("userInfo");
        if (userInfo == null)
            return;

        //表头数据
        List<String> header = new ArrayList<String>();
        header.add("姓名");
        header.add("学号");
        header.add("学院");
        header.add("班级");

        //数据内容
        Task task = taskService.getById(taskId);

        if (task == null)
            return;

        Template template = templateService.getById(task.getTaskTemplate());

        if (template == null)
            return;

        System.out.println("任务模板内容：" + template);

        String fields = template.getTemplateFields();
        JSONArray object = JSON.parseArray(fields);
        for (Object o : object) {
            JSONObject jsonObject = JSON.parseObject(o.toString());
            String value = jsonObject.getString("value");
            System.out.println("表头：" + value);
            header.add(value);
        }

        QueryWrapper<Report> queryWrapper = new QueryWrapper<Report>();
        queryWrapper.eq("task_id", taskId).eq("deleted",0);
        List<Report> reportAll = reportService.getReportAll(taskId);

        List<List<String>> student = new ArrayList<List<String>>();
        int j = 0;
        for (Report report : reportAll) {
            List<String> re = new ArrayList<String>();
            re.add(report.getSname());
            re.add(report.getSno());
            re.add(report.getCollege());
            re.add(report.getCname());

            System.out.println("学生姓名：" + report.getSname());

            String reportContent = report.getReportContent();
            String[] split = reportContent.split("&");
            for (String s : split) {
                String[] strings = s.split("=");
                System.out.println("打印值：" + strings[1]);
                re.add(strings[1]);
            }
            System.out.println("学生信息载入成功");
            student.add(re);
        }

        //声明一个工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();

        //生成一个表格，设置表格名称为"学生表"
        HSSFSheet sheet = workbook.createSheet("学生表");

        //设置表格列宽度为10个字节
        sheet.setDefaultColumnWidth(10);

        //创建第一行表头
        HSSFRow headrow = sheet.createRow(0);

        //遍历添加表头(下面模拟遍历学生，也是同样的操作过程)
        int i =0;
        for (String s : header) {
            //创建一个单元格
            HSSFCell cell = headrow.createCell(i);
            //创建一个内容对象
            HSSFRichTextString text = new HSSFRichTextString(s);
            //将内容对象的文字内容写入到单元格中
            cell.setCellValue(text);
            // 移到下一行
            i++;
        }

        // 添加学生
        int n =1;
        for (List<String> strings : student) {
            System.out.println("打印学生：" + strings );
            // 创建新的行
            HSSFRow row1 = sheet.createRow(n);
            int m =0;
            for (String string : strings) {
                // 对URL编码进行解码
                String decode = URLDecoder.decode(string);

                System.out.println("打印学生信息：" + decode);

                // 创建一个新的单元格
                HSSFCell cell = row1.createCell(m);
                HSSFRichTextString text = new HSSFRichTextString(decode);
                cell.setCellValue(text);
                m++;
            }
            n++;
        }

        //准备将Excel的输出流通过response输出到页面下载
        //八进制输出流
        response.setContentType("application/octet-stream");

        System.out.println("任务名称： " + task.getTaskName());
        //这后面可以设置导出Excel的名称，此例中名为student.xls
        response.setHeader("Content-disposition", "attachment;filename="+ new SimpleDateFormat("yyMMddHHmmss").format(new Date()) + "_" + PinYin.toFirstChar(task.getTaskName()).toUpperCase() +".xls");

        //刷新缓冲
        response.flushBuffer();

        //workbook将Excel写入到response的输出流中，供页面下载
        workbook.write(response.getOutputStream());
    }
}
